package service

import (
	"github.com/jmoiron/sqlx"
	"web_framework/model"
	"web_framework/storage"
	. "web_framework/pkg/e"
	"github.com/goinggo/mapstructure"
)

//获取初始化配置
func GetDownloadConfigCache(db sqlx.Queryer, id int) (model.DownloadConfig, error) {
	var (
		downloadConfigMap map[string]interface{}
		err error
		download model.DownloadConfig
	)
	if res,_ := storage.RedisHExists(storage.RouterDownLoadConfig , "hbInterval");res{
		downloadConfigMap,err = storage.RedisHGetAll(storage.RouterDownLoadConfig)
		if err != nil{
			Log("err" , "获取初始化配置缓存失败" ,  err.Error())
			return download,err
		}
	}else {
		downLoadDb,err := storage.GetDownloadConfig(db , id)
		if err != nil{
			return download, err
		}else{
			downloadConfigMap = map[string]interface{}{
				"hbInterval":downLoadDb.HbInterval,
				"hb_device_num":downLoadDb.HbDeviceNum,
				"scan_return_page":downLoadDb.ScanReturnPage,
				"search_return_page":downLoadDb.SearchReturnPage,
				"up_speed":downLoadDb.UpSpeed,
				"down_speed":downLoadDb.DownSpeed,
			}
			_, setErr := storage.RedisHSet(storage.RouterDownLoadConfig, downloadConfigMap, -1)
			if setErr != nil {
				Log("err", "初始化配置缓存失败")
			}
		}
	}

	if err := mapstructure.Decode(downloadConfigMap, &download); err != nil {
		Log("err", "初始化配置转结构体失败")
	}
	return download, nil
}
